canvas.addEventListener('mousedown', handleClick, false);
canvas.addEventListener('mouseup',handleUnclickLeft,false);
canvas.addEventListener('contextmenu',handleUnclickRight, false);
canvas.addEventListener('mousemove', handleMove, false);
canvas.addEventListener('mouseout',handleOut, false);

document.body.addEventListener('keydown', handleKeydown, false);

//click
function handleClick(e) {}

//left unclick
function handleUnclickLeft(e) {
    //return si bouton droit de la souris, la bonne méthode sera appelée ensuite
    if(e.which == 3) return;

    var gridCoordClick = findRowCol(undefined, e.clientX, e.clientY);
    var rowClick = gridCoordClick.row;
    var colClick = gridCoordClick.col;

    //Si on est en train de placer un bâtiment
    if(ghost_isBuildingSmtg) {
        //Si la construction a réussie, on recréer une instance de bâtiment fantôme
        //pour un éventuel second placement
        if(ghost_item.tryCreateBuilding()) {
            ghost_item = new GhostBuilding(ghost_item.type);
           //TODO update not working ? quoilebaise ?
            cl_hero_update(hero.asSimpleObject());
//                console.log('sent to srv : ');
//                console.log(hero.asSimpleObject());
        }
    }
    //Si on séléctionne un bâtiment pour storage
    else if(isSelectingBuilding) {

        if (rowClick >= 0 && colClick >= 0 && rowClick < grid.width && colClick < grid.height) {
            if(tileMap[rowClick][colClick].building != null) {
                var building = tileMap[rowClick][colClick].building;
                harvestAndStore(building);
            }
        }
    }
    //Sinon, déplacement du héros
    else {
        // Si on est sur la map
        if (rowClick >= 0 && colClick >= 0 && rowClick < grid.width && colClick < grid.height) {
            if(tileMap[rowClick][colClick].canPass == 1) {
//            console.log('click on tile : '+rowClick+','+colClick+' id = '+tileMap[rowClick][colClick].id);
                startAstar(rowClick,colClick);
            }
        }
    }

}

//right unclick
function handleUnclickRight(e) {
    e.preventDefault();
    //Si l'user était en train de placement un building / une crop
    //On annule le placement et on redraw la zone (disparition du fantôme)
    if(ghost_isBuildingSmtg){
        ghost_isBuildingSmtg = false;
        drawRange(ghost_curTile,3);
        return;
    }
    else if(isSelectingBuilding){
        isSelectingBuilding = false;
        ui_right.style.visibility = 'collapse';
    }
    else {
        var gridCoordClick = findRowCol(undefined, e.clientX, e.clientY);
        var rowClick = gridCoordClick.row;
        var colClick = gridCoordClick.col;

        var tileClicked = findTileByRowCol(rowClick,colClick);

        //tiles neutres ou alliées
        if(tileClicked.heroId == null || tileClicked.heroId == hero.id) {
            ui_right.style.visibility = 'visible';
            setupInfoPanel(tileClicked);
        }else {
            ui_right.style.visibility = 'collapse';
        }
    }

//    console.log('click on tile : '+rowClick+','+colClick+' with coords : '
//        +tileMap[rowClick][colClick].x
//        +','
//        +tileMap[rowClick][colClick].y);
}

//mousemove
function handleMove(e) {
    //Si on construit qqchose (gestion du fantôme building / crop)
    if(ghost_isBuildingSmtg) {
        var gridCoordMove = findRowCol(undefined, e.clientX, e.clientY);
        var rowMove = gridCoordMove.row;
        var colMove = gridCoordMove.col;

        // Si on est sur la map
        if (rowMove >= 0 && colMove >= 0 && rowMove < grid.width && colMove < grid.height) {
            ghost_curTile = findTileByRowCol(gridCoordMove.row,gridCoordMove.col);

            //Si on a changé de tile avec le fantôme, on efface et on redessine la zone
            if(ghost_curTile != ghost_prevTile) {
                drawRange(ghost_curTile,3);
                ghost_item.drawGhost();

                if(findCurHeroTile(hero) == ghost_curTile) hero.drawHero();
                if(findCurHeroTile(hero) == ghost_prevTile) hero.drawHero();

                ghost_prevTile = ghost_curTile;
            }
        }
    }
}

//mouseout
function handleOut(e) {

}

//keydown
function handleKeydown(e) {
    switch (e.keyCode) {
//        case keys.UP:
//        case keys.Z:
//            camera.y += 60;
//            break;
//        case keys.DOWN:
//        case keys.S:
//            camera.y -= 60;
//            break;
//        case keys.LEFT:
//        case keys.Q:
//            camera.x += 60;
//            break;
//        case keys.RIGHT:
//        case keys.D:
//            camera.x -= 60;
//            break;
        case keys.B:
            console.log(debugMsg);
            break;
    }
}

//resize
window.onresize = function() {
    setCanvas();
    setUI();
}

//refresh / close / url change
//window.onbeforeunload = function(e) {
//    if(hero.connected) {
//        cl_leave_event(hero.getHeroLeaveState());
//        for(var i = 0; i = -1; i++) {
//            if(i == 1000) break;
//        }
//    }
//}

function captureTile() {
    var tile = selectedTile;

    //si la tile est neutre
    if(tile.heroId == null) {
        tile.img = tile_owned;
        tile.heroId = hero.id;

        hero.addTile(tile.asSimpleObject());
        hero.level = hero.tiles.length;

        tile.drawTile();

        cl_tile_update(tile.asSimpleObject());

    }
    //TODO handle FIGHTS !
    else {
        console.log('FIGHT !');
    }

    cl_hero_update(hero.asSimpleObject());
    updHeroStats();

    ui_right.style.visibility = 'collapse';
}

function destroyCrop() {
    var crop = selectedCrop;
    var cropTile = findTileByRowCol(crop.pos.row, crop.pos.col);
    if(selectedCrop.timerHandler != false) {
        clearInterval(selectedCrop.timerHandler);
    }
    hero.removeCrop(crop);

    cl_crop_deleted(crop.pos);
    cl_hero_update(hero.asSimpleObject());
    updHeroStats();

    ui_right.style.visibility = 'collapse';
}

function harvestAndSell() {
    var crop = selectedCrop;
    if(selectedCrop.timerHandler != false) {
        clearInterval(selectedCrop.timerHandler);
    }
    hero.updateGolds(crop.seedPrice);
    hero.removeCrop(crop);

    cl_crop_deleted(crop.pos);
    cl_hero_update(hero.asSimpleObject());
    updHeroStats();

    ui_right.style.visibility = 'collapse';
}

function storingState() {
    isSelectingBuilding = true;
    gameMsg('Left click on a building to store, or rightclick to cancel');
}

function harvestAndStore(building) {
    var crop = selectedCrop;
    //si on a réussi a stocker
    if(building.addToStock(crop) == true) {
        if(selectedCrop.timerHandler != false) {
            clearInterval(selectedCrop.timerHandler);
        }

        isSelectingBuilding = false;

        hero.removeCrop(crop);

        cl_crop_deleted(crop.pos);
        cl_hero_update(hero.asSimpleObject());

        ui_right.style.visibility = 'collapse';
    }
}

function sellFromBuilding() {
    var building = selectedBuilding;

    for(var p=0; p<building.stock.length; p++) {
        var price = building.stock[p].price;
        hero.updateGolds(price);
    }

    building.clearStock();

    updHeroStats();
    cl_hero_update(hero.asSimpleObject());
    ui_right.style.visibility = 'collapse';
}

//Game Buildings & Crops Click events
function btnBuildSiloClick() {
    ghost_isBuildingSmtg = true;
    ghost_curTile = findCurHeroTile(hero);
    ghost_prevTile = findCurHeroTile(hero);
    ghost_item = new GhostBuilding(BUILDINGS.SILO);
}

function btnBuildBarnClick() {
    ghost_isBuildingSmtg = true;
    ghost_curTile = findCurHeroTile(hero);
    ghost_prevTile = findCurHeroTile(hero);
    ghost_item = new GhostBuilding(BUILDINGS.BARN);
}

function btnBuildColdStorageClick() {
    ghost_isBuildingSmtg = true;
    ghost_curTile = findCurHeroTile(hero);
    ghost_prevTile = findCurHeroTile(hero);
    ghost_item = new GhostBuilding(BUILDINGS.COLDSTORAGE);
}

function btnCropTomatoClick() {
    ghost_isBuildingSmtg = true;
    ghost_curTile = findCurHeroTile(hero);
    ghost_prevTile = findCurHeroTile(hero);
    ghost_item = new GhostBuilding(CROPS.TOMATO);
}

function btnCropCornClick() {
    ghost_isBuildingSmtg = true;
    ghost_curTile = findCurHeroTile(hero);
    ghost_prevTile = findCurHeroTile(hero);
    ghost_item = new GhostBuilding(CROPS.CORN);
}

function btnCropWheatClick() {
    ghost_isBuildingSmtg = true;
    ghost_curTile = findCurHeroTile(hero);
    ghost_prevTile = findCurHeroTile(hero);
    ghost_item = new GhostBuilding(CROPS.WHEAT);
}

function btnClosePanelClick() {
    ui_right.style.visibility = 'collapse';
}

//
//function btnGetInfoClick() {
//    newPlayerOnMap();
//}